package com.maoye.ossp.sys.log.aspect;

import java.util.Date;
import java.util.StringTokenizer;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.JoinPoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.hotent.base.db.api.IdGenerator;
import com.maoye.ossp.sys.log.entity.SysLog;
import com.maoye.ossp.sys.log.service.ISysLogService;
import com.maoye.ossp.sys.org.util.UserUtils;


public class AspectLog {
		protected Logger logger = LoggerFactory.getLogger(getClass());
		@Resource
		private ISysLogService IsysLogService;
		@Resource
		public IdGenerator idGenerator;
		@Resource
		private HttpServletRequest request;
		//定义方法名
	    String strLog = null ;  
	      
	    /** 
	     * 前置通知：在某连接点之前执行的通知，但这个通知不能阻止连接点前的执行 
	     * @param jp 连接点：程序执行过程中的某一行为，例如，AServiceImpl.barA()的调用或者抛出的异常行为 
	     */  
	   /* public void doBefore(JoinPoint jp) {  
	        strLog = jp.getTarget().getClass().getName() + "."  
	                + jp.getSignature().getName(); 
	        //获取Ip地址
	        InetAddress addr=null;
			try {
				addr = InetAddress.getLocalHost();
			} catch (UnknownHostException e) {
				e.printStackTrace();
			}
	        String ip=addr.getHostAddress().toString();//获得本机IP
	        //获取插入数据时间
	        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	        String date = sdf.format(new Date());
	        Object[]o = jp.getArgs();
	        for(Object ob : o){
	        	System.out.println("参数名:"+ob);
	        	strLog+=o;
	        }
	        
	    }*/  
	    /** 
	     * 环绕通知：包围一个连接点的通知，可以在方法的调用前后完成自定义的行为，也可以选择不执行 
	     * 类似Web中Servlet规范中的Filter的doFilter方法。 
	     * @param pjp 当前进程中的连接点 
	     * @return 
	     * @throws Throwable 
	     *//*  
	    public Object doAround(ProceedingJoinPoint pjp) throws Throwable {  
	        long time = System.currentTimeMillis();  
	        Object retVal = pjp.proceed();  
	        time = System.currentTimeMillis() - time;  
	        System.out.println("process time: " + time + " ms");  
	        return retVal;  
	    }  */
	    /** 
	     * 抛出异常后通知 ： 在方法抛出异常退出时执行的通知。 
	     * @param jp 连接点：程序执行过程中的某一行为，例如，AServiceImpl.barA()的调用或者抛出的异常行为 
	     */  
	    public void doAfter(JoinPoint jp) {  
	    	SysLog log = new SysLog();
	    	//方法名 Method
	    	strLog =jp.getSignature().getName(); 
	    	Object[] args = jp.getArgs();
	    	String param ="";//方法参数
	    	if(args!=null){
		    	for(Object obj : args){
		    		if(obj!=null){
		    			param +=obj.toString()+";";
		    		}
		    	}
	    	}
	    	if(param.length()>2000){
	    		param = param.substring(0,2000);
	    	}
	        //获取用户代理
	        String Agent = request.getHeader("User-Agent");
	        StringTokenizer st = new StringTokenizer(Agent,";");
	        //得到用户的浏览器名
	        String userbrowser = st.nextToken();
	        String uri = request.getRequestURI().toString();
	        Long uid = UserUtils.getCurrentUserId();
			try {
				String ip=request.getRemoteAddr();//获得本机IP
		        Date date = new Date();		        
		        log.setId(idGenerator.getUId());
		        log.setCreateBy(uid.toString());
		        log.setCreateTime(date);
		        log.setIp(ip);
		        log.setMethod(request.getMethod());
		        log.setParameter(param);
		        log.setType(LogTypeConstant.Normal_type);
		        log.setUserAgent(userbrowser);
		        log.setUri(uri);
		        IsysLogService.buildLog(log);
			} catch (Exception e) {
				logger.error(e.getMessage());
			}
	    }  
	    
	    /**
	     * 对系统日志的异常和信息进行记录
	     * @param jp
	     * @param ex
	     * @author yanzy
	     * @data 2014年6月16日
	     */
	    public void doError(JoinPoint jp, Throwable ex){
	    	SysLog log = new SysLog();
	    	//方法名 Method
	    	strLog =jp.getSignature().getName(); 
	    	Object[] args = jp.getArgs();
	    	String param ="";//方法参数
	    	if(args!=null){
		    	for(Object obj : args){
		    		if(obj!=null){
		    			param +=obj.toString()+";";
		    		}
		    	}
	    	}	
	        //获取用户代理
	        String Agent = request.getHeader("User-Agent");
	        StringTokenizer st = new StringTokenizer(Agent,";");
	        //得到用户的浏览器名
	        String userbrowser = st.nextToken();
	        String uri = request.getRequestURI().toString();
	        Long uid = UserUtils.getCurrentUserId();
	        //记录异常信息
	        String exception ="";
	        StackTraceElement [] stacks = ex.getStackTrace();
	        int length = stacks.length;
	        for(int i=0;i<length;i++){
	        	exception += stacks[i].toString();
	        }
			try {
				String ip=request.getRemoteAddr();//获得本机IP
		        Date date = new Date();		        
		        log.setId(idGenerator.getUId());
		        log.setCreateBy(uid.toString());
		        log.setCreateTime(date);
		        log.setIp(ip);
		        log.setMethod(request.getMethod());
		        log.setParameter(param);
		        log.setType(LogTypeConstant.Exception_type);
		        log.setUserAgent(userbrowser);
		        log.setUri(uri);
		        log.setException(exception);
		        IsysLogService.buildLog(log);
			} catch (Exception e) {
				logger.error(e.getMessage());
			}
	    }
	    
		
}

